import { Component, OnInit, ViewChild } from '@angular/core';
import { _HttpClient, ModalHelper } from '@delon/theme';
import { SimpleTableColumn, SimpleTableComponent, SimpleTableButton, XlsxService } from '@delon/abc';
import { SFSchema } from '@delon/form';
import { UserService } from '../../../service/user/user.service';
import { AgentUserListEditComponent } from './edit/edit.component';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { NzMessageBaseService, NzMessageService, NzModalService, UploadFile, NzNotificationService } from 'ng-zorro-antd';
import { UserPriceConfigModalComponent } from '@shared/component/userprice/user-price-config-modal.component';
import { ProductService } from '../../../service/prod/product.service';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { CommService } from '../../../service/comm/comm.service';
import { ServiceResult } from '@core/constant';
import { format } from 'date-fns';

@Component({
  selector: 'agent-user-list',
  templateUrl: './agent-list.component.html',
  providers: [TranslatePipe]
})
export class AgentUserListComponent implements OnInit {
  ps = 10;
  q: any = {
    userLevel: 'FIRST',
    name: ''
  };
  uploadCurrencyCodeLabelUrl = this.user.batchSetCurrencyCodeLabel();
  extraParam = { type: 'YUAN' };
  extraParam2 = { type: 'DOLLOR' };
  url = this.user.list();
  data = [];
  checkedList = [];
  loading = false;
  loading2 = false;
  loading3 = false;
  status_normal = null;



  @ViewChild('st') st: SimpleTableComponent;
  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '账号', index: 'username', i18n: 'account' },
    { title: '名称', index: 'name', i18n: 'name' },
    { title: '负责人', index: 'zname' },
    { title: '标签', index: 'label', render: 'label' },
    { title: '地址', index: 'address', i18n: 'address', render: 'address' },
    { title: '币种', index: 'currency', i18n: 'currency' },
    { title: '公司代码', index: 'siteCode', i18n: 'siteCode' },
    { title: '价格配置', index: 'priceConfig', render: 'priceConfig', i18n: 'priceConfig',
      tag: {
        'DEFAULT': { text: 'default', color: 'geekblue' },
        'CALC': { text: 'calc', color: 'orange' },
        'CONFIG': { text: 'config', color: 'purple' },
      }
    },
    { title: '状态', index: 'isDisabled', i18n: 'status', render: 'isDisabled' },
    {
      title: '',
      buttons: [
        {
          text: "编辑",
          i18n: 'edit',
          type: 'modal',
          component: AgentUserListEditComponent,
          modal: {modalOptions: {nzStyle: {'top': '24px'}}},
          paramName: 'record',
          params: (record: any) => {
            return { id: `${record.id}` }
          },
          size: 800,
          click: (record: any, modal: any) => this.st.reload()
        },
        {
          text: '禁用',
          i18n: 'disable',
          pop: true,
          popTitle: 'Account disable?',
          iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
            return item.isDisabled === '0';
          },
          click: (record: any) =>this.disable(record.id)
        },
        {
          text: '解禁',
          i18n: 'enable',
          pop: true,
          popTitle: 'Account enable?',
          iif: (item: any, btn: SimpleTableButton, column: SimpleTableColumn) => {
            return item.isDisabled === '1';
          },
          click: (record: any) =>this.enable(record.id)
        }
      ]
    }
  ];

  constructor(
    private transPipe: TranslatePipe,
    private trans: TranslateService,
    private notice: NzNotificationService,
    private modalService: NzModalService,
    private msg: NzMessageService,
    private user: UserService,
    private prodService: ProductService,
    private modal: ModalHelper,
    private xlsx: XlsxService,
    private comm: CommService
  ) { }

  ngOnInit() {
    this.loadLabels();
    this.loadCurrency();
    this.loadSiteCode();
  }



  add() {
    this.modal.static(AgentUserListEditComponent, null, 600, {nzStyle: {'top': '24px'}}).subscribe((e) => {
        this.st.load(1, this.q);
    });
  }

  enable(id) {
    let lang = this.trans.currentLang || this.trans.defaultLang;
    this.user.enable(id).pipe(
        catchError(err => {
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success(lang === 'en' ? 'Successful' : '操作成功');
            this.st.load(1, this.q);
        } else {
            this.msg.error(ret.message);
        }
    });
  }

  disable(id) {
    let lang = this.trans.currentLang || this.trans.defaultLang;
    this.user.disable(id).pipe(
        catchError(err => {
            return of(err);
        })
    ).subscribe(ret=>{
        if (ret.status === 200) {
            this.msg.success(lang === 'en' ? 'Successful' : '操作成功');
            this.st.load(1, this.q);
        } else {
            this.msg.error(ret.message);
        }
    });
  }

  openConfig() {
    // if (this.checkedList.length == 0) {
    //   this.msg.warning('Please select account');
    //   return;
    // }
    let ids = this.checkedList.length === 0 ? '' : this.checkedList.map(v => { return v.id });
    const modal = this.modalService.create({
      nzTitle: 'Batch configure price',
      nzContent: UserPriceConfigModalComponent,
      nzCancelText: 'cancel',
      nzOkText: 'Confirm',
      nzOnOk: (priceModal) => {
        if (!priceModal.radioValue) {
          this.msg.warning('Please select one');
          return false;
        }
        if (priceModal.radioValue === 'B' && !priceModal.calc) {
          this.msg.warning('Please input a number');
          return false;
        }
        let config = 'DEFAULT';
        if (priceModal.radioValue === 'A') {
          config = 'DEFAULT';
        } else if (priceModal.radioValue === 'B') {
          config = 'CALC';
        } else if (priceModal.radioValue === 'C') {
          config = 'CONFIG';
        }
        this.user.setPriceConfig({ id: ids.toString(), config: config,
            method: priceModal.selectedValue, calc: priceModal.calc}).pipe(
          catchError(err => {
            return of(err)
          })
        ).subscribe(data => {
          if (data.status === 200) {
            this.msg.success("Successful");
            modal.destroy();
            this.checkedList = [];
            this.st.reload();
          } else {
            this.msg.error("Error:" + data.message);
          }
        })
        return false;
      }
    });
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
        this.loading = true;
    }
    if (info.file.status === 'done') {
        this.loading = false;
        this.notice.create('success', 'Successful', 'The price config upload successful!');
    }
    if (info.file.status === 'error') {
        this.loading = false;
        this.notice.create('error', 'Error', 'The price config upload failed!');
    }
  }

  handleChange2(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
        this.loading2 = true;
    }
    if (info.file.status === 'done') {
        this.loading2 = false;
        this.notice.create('success', 'Successful', 'The price config upload successful!');
    }
    if (info.file.status === 'error') {
        this.loading2 = false;
        this.notice.create('error', 'Error', 'The price config upload failed!');
    }
  }

  handleChange3(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading3 = true;
    }
    if (info.file.status === 'done') {
      this.loading3 = false;
      this.notice.create('success', 'Success', info.file.response.data['successTip']);
      if (undefined !== info.file.response.data['failTip']) {
        this.notice.create('info', 'Info', info.file.response.data['failTip']);
      }
      this.st.load();
    }
    if (info.file.status === 'error') {
      this.loading3 = false;
      this.notice.create('error', 'Error', info.file.response.msg);
    }
  }

  download() {
    let data = [["留空", "[用户账号]"]];
    if (this.checkedList.length != 0) {
      let tmp = ["留空"];
      this.checkedList.forEach(i => {
        tmp.push(i.username);
      });
      data = [tmp];
    }
    data.push(["[产品代码]"]);
    this.xlsx.export({
      sheets: [
        {
          data: data,
          name: 'jia',
        },
      ],
    });
  }

  getMethod(m) {
    if (m === 'PLUS') {
      return '+';
    } else if (m === 'MINUS') {
      return '-';
    } else if (m === 'MULT') {
      return "*";
    } else {
      return '/';
    }
  }

  cancel() {
    this.currency = null;
  }

  cancel2() {
    this.siteCode = null;
  }

  cancel3() {
    this.label = null;
  }

  setCurrency() {

    if (!this.currency) {
      this.msg.warning('The currency is required');
      return;
    }
    let ids = this.checkedList.length === 0 ? '' : this.checkedList.map(v => { return v.id });
    this.user.setCurrency({id: ids.toString(), currency: this.currency}).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(data => {
      if (data.status === 200) {
        this.msg.success('Successful');
        this.st.reload(this.q);
        this.checkedList = [];
      } else {
        this.msg.error(data.message);
      }
      this.currency = null;
    })
  }

  setSiteCode() {
    if (!this.siteCode) {
      this.msg.warning('The sitecode is required');
      return;
    }
    let ids = this.checkedList.length === 0 ? '' : this.checkedList.map(v => { return v.id });
    this.user.setSiteCode({id: ids.toString(), siteCode: this.siteCode}).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(data => {
      if (data.status === 200) {
        this.msg.success('Successful');
        this.st.reload(this.q);
        this.checkedList = [];
      } else {
        this.msg.error(data.message);
      }
      this.siteCode = null;
    })
  }

  setLabel() {
    if (!this.label) {
      this.msg.warning('The label is required');
      return;
    }
    let ids = this.checkedList.length === 0 ? '' : this.checkedList.map(v => { return v.id });
    this.user.setLabel({id: ids.toString(), label: this.label}).pipe(
      catchError(err => {
        return of(err)
      })
    ).subscribe(data => {
      if (data.status === 200) {
        this.msg.success('Successful');
        this.st.reload(this.q);
        this.checkedList = [];
      } else {
        this.msg.error(data.message);
      }
      this.label = null;
    })
  }
  label = null;
  labels = [];
  currency = null;
  currencys = [];
  siteCode = null;
  siteCodes = [];

  loadLabels() {
    this.labels = [];
    this.comm.getLabels().subscribe(data => {
        const ret: ServiceResult = <ServiceResult> data;
        if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.labels.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
          }
        }
    })
  }

  // 加载货币类型
  loadCurrency() {
    this.currencys = [];
    this.comm.getCurrencys().subscribe(data => {
        const ret: ServiceResult = <ServiceResult> data;
        if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.currencys.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
          }
        }
    })
  }

  loadSiteCode() {
    this.siteCodes = [];
    this.comm.getSiteCodes().subscribe(data => {
        const ret: ServiceResult = <ServiceResult> data;
        if (ret.status === 200) {
          for (const row of ret['data']['rows']) {
              this.siteCodes.push({ text: (row.labelEnUs).toUpperCase(), value: row.value });
          }
        }
    })
  }

  sync() {
    if (!this.repdate) {
      this.msg.warning('Please input sync date');
      return false;
    }
    this.loading = true;
    const id = this.msg.loading('Syncing..', { nzDuration: 0 }).messageId;
    this.user.sync(format(this.repdate, "YYYYMMDD")).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.loading = false;
      this.msg.remove(id);
      if (data.status === 200) {
        this.msg.success('Sync successful');
        this.st.load(1);
        this.repdate = null;
      } else {
        this.msg.error(data.message);
      }
    })
  }

  cancelSync() {
    this.repdate = null;
  }
  repdate = null;
}
